#include "shm.h"

// 客户端与服务端的shm模块要同步
#define SHM_PATHNMAE "../../shm"
#define SHM_PROJ_ID 66

enum shm_create_status shm_create(size_t size, int *pshmid)
{
    int shmid;
    key_t key;

    key = ftok(SHM_PATHNMAE, SHM_PROJ_ID);

    shmid = shmget(key, size, 0); // 获取共享内存
    if (-1 == shmid)
    {
        shmid = shmget(key, size, IPC_CREAT | 0644); // 创建共享内存
        if (-1 == shmid)
        {
            perror("[ERROR] shmget()");
            return SHM_CREATE_ERROR;
        }

        *pshmid = shmid;
        return SHM_CREATE_NEW;
    }
    // 共享内存已存在
    else
    {
        *pshmid = shmid;
        return SHM_HAS_EXIST;
    }
}

// 共享内存映射
void *shm_at(int shmid)
{
    void *addr;

    addr = shmat(shmid, NULL, 0);
    if (addr == (void *)-1)
    {
        perror("[ERROR] shmat()");
        return NULL;
    }

    return addr;
}

// 共享内存解除映射
int shm_dt(void *addr)
{
    return shmdt(addr);
}

// 删除共享内存
int shm_delete(int shmid)
{
    return shmctl(shmid, IPC_RMID, NULL);
}